const crypto = require('crypto');
const jwt = require('jsonwebtoken');

const default_jwtKey = 'RgVRWFBHGShKILJWDHukepzL2axpkp9epV'
const jwtKey = get_jwtKey();

function get_jwtKey() {
    if (process.env.JWT_KEY) {
        return process.env.JWT_KEY;
    } else {
        console.log(`请管理员检查是否在测试环境运行，本次运行采用的是默认jwtkey: ${default_jwtKey}`);
        return default_jwtKey;
    }
}

function sha256(input) {
    return crypto.createHash('sha256').update(input).digest('hex');
}

async function verifyJwtToken(token) {
    // 此处的 code 返回 0-登录验证失败 1-验证成功但超时 2-验证成功并且未超时
    // 异步转同步 强制立即执行jwt的解码操作
    let result = await new Promise((resolve, reject) => {
        jwt.verify(token, jwtKey, (err, decoded) => {
            if (err) {
                reject({ msg: "登录验证失败，请重新登录", login: false, err: err, code: 0 });
            } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
                reject({ msg: "登录超时，请重新登录", login: false, err: err, code: 1 });
            } else {
                resolve({ msg: "登录成功", login: true, data: decoded, code: 2 });
            }
        });
    });
    return result;
}

/*
 * 提供用户登录状态的非敏感数据
 * 提供过期时间: exp = {expiresIn: '168h'}
 */
async function createUserJwtToken(data, exp) {
    let token = jwt.sign(data, jwtKey, exp);
    return token;
}

module.exports = {jwt, jwtKey, sha256, verifyJwtToken, createUserJwtToken};
